package com.dashu.core.service;

import com.dashu.base.enums.ReplRyCode;
import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.UIDUtil;
import com.dashu.base.utils.VerificationUtil;
import com.dashu.core.dto.company.CompanyDTO;
import com.dashu.core.dto.gate.GateOutTimeDTO;
import com.dashu.core.handler.VerificationException;
import com.dashu.core.model.GateOutTime;
import com.dashu.core.model.QGateOutTime;
import com.dashu.core.vo.UpdateEntityVO;
import com.dashu.core.vo.gate.GateOutTimeVO;
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.FlushModeType;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GateOutTimeService extends DataService {
    @Autowired
    private GateDateService gateDateService;
    @Autowired
    private CompanyService companyService;

    @Transactional
    public GateOutTimeDTO add(GateOutTimeVO gateDateVO) {
        GateOutTime gateOutTime = CopyUtil.copyEnty(gateDateVO, GateOutTime.class);
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            gateOutTime.setCreateUser(userId);
            gateOutTime.setBaseId(userId);
            entityManager.persist(gateOutTime);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        GateOutTimeDTO gateDateDTO = CopyUtil.copyEnty(gateOutTime, GateOutTimeDTO.class);
        return gateDateDTO;

    }

    @Transactional
    public GateOutTimeDTO addDefult(long baseId) {
        GateOutTime gateOutTime = new GateOutTime();
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            gateOutTime.setId(UIDUtil.nextId());
            gateOutTime.setCreateUser(userId);
            gateOutTime.setCreateTime(System.currentTimeMillis());
            gateOutTime.setBaseId(baseId);
            gateOutTime.setIsDefult(0);
            gateOutTime.setStartDate1("08:00");
            gateOutTime.setEndDate1("11:00");
            gateOutTime.setStartDate2("14:00");
            gateOutTime.setEndDate2("18:00");
            gateOutTime.setStartDate3("19:00");
            gateOutTime.setEndDate3("21:00");
            gateOutTime.setName("默认考勤");
            gateOutTime.setOpen("1,1,1");
            entityManager.persist(gateOutTime);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        GateOutTimeDTO gateDateDTO = CopyUtil.copyEnty(gateOutTime, GateOutTimeDTO.class);
        return gateDateDTO;

    }

    @Transactional
    public boolean deleteGateData(long timeId) {
        QGateOutTime qGateOutTime = QGateOutTime.gateOutTime;
//        List<GateDateDTO> gateDateDTOS = gateDateService.findGateOutTime(timeId);
//        if (gateDateDTOS.size() > 0)
//            throw new VerificationException(ReplRyCode.ATTENDANCE_RULE_TIME, ReplRyCode.ATTENDANCE_RULE_TIME.getMessage());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qGateOutTime.id.eq(timeId));

        List<GateOutTime> gateOutTimes =
                queryFactory
                        .select(qGateOutTime)
                        .from(qGateOutTime)
                        .where(booleanBuilder.getValue())
                        .fetch();
        gateOutTimes.stream().forEach(ad -> {
            entityManager.remove(ad);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        });
        return true;

    }

    @Transactional
    public GateOutTimeDTO updataGateData(UpdateEntityVO<GateOutTimeVO> gateDateVO) throws Exception {
        QGateOutTime qGateOutTime = QGateOutTime.gateOutTime;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        GateOutTimeVO gateOutTimeVO = gateDateVO.getEntityVO();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qGateOutTime.id.eq(gateDateVO.getId()));
        GateOutTime gateOutTime =
                queryFactory
                        .select(qGateOutTime)
                        .from(qGateOutTime)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        if (gateOutTime == null)
            throw new VerificationException(ReplRyCode.ATTENDANCE_NOT_TIME, ReplRyCode.ATTENDANCE_NOT_TIME.getMessage());
        if (gateOutTimeVO.getStartDate1() != null)
            gateOutTime.setStartDate1(gateOutTimeVO.getStartDate1());
        if (gateOutTimeVO.getStartDate2() != null)
            gateOutTime.setStartDate2(gateOutTimeVO.getStartDate2());
        if (gateOutTimeVO.getStartDate3() != null)
            gateOutTime.setStartDate3(gateOutTimeVO.getStartDate3());
        if (gateOutTimeVO.getEndDate1() != null)
            gateOutTime.setEndDate1(gateOutTimeVO.getEndDate1());
        if (gateOutTimeVO.getEndDate2() != null)
            gateOutTime.setEndDate2(gateOutTimeVO.getEndDate2());
        if (gateOutTimeVO.getEndDate3() != null)
            gateOutTime.setEndDate3(gateOutTimeVO.getEndDate3());
        if (!StringUtils.isEmpty(gateOutTimeVO.getOpen()))
            gateOutTime.setOpen(gateOutTimeVO.getOpen());
        gateOutTime.setUpdateUser(userId);
        gateOutTime.setUpdateTime(new Date().getTime());
        gateOutTime = entityManager.merge(gateOutTime);
        entityManager.setFlushMode(FlushModeType.AUTO);
        GateOutTimeDTO CompanyClsDTO = CopyUtil.copyEnty(gateOutTime, GateOutTimeDTO.class);
        return CompanyClsDTO;

    }


    public GateOutTimeDTO findGateGroup(long timeId) {
        QGateOutTime qGateOutTime = QGateOutTime.gateOutTime;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qGateOutTime.id.eq(timeId));
        GateOutTime gateOutTime =
                queryFactory
                        .select(qGateOutTime)
                        .from(qGateOutTime)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        GateOutTimeDTO gateOutTimeDTO = CopyUtil.copyEnty(gateOutTime, GateOutTimeDTO.class);
        return gateOutTimeDTO;

    }

    public long count(String timeName) throws Exception {
        QGateOutTime qGateOutTime = QGateOutTime.gateOutTime;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qGateOutTime.createUser.eq(userId));
        if (!StringUtils.isEmpty(timeName))
            booleanBuilder.and(qGateOutTime.name.eq(timeName));
        long count =
                queryFactory
                        .select(qGateOutTime)
                        .from(qGateOutTime)
                        .where(booleanBuilder.getValue())
                        .fetchCount();
        return count;

    }

    public List<GateOutTimeDTO> findByBaseUser(String timeName) throws Exception {
        QGateOutTime qGateOutTime = QGateOutTime.gateOutTime;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qGateOutTime.createUser.eq(userId));
        if (!StringUtils.isEmpty(timeName))
            booleanBuilder.and(qGateOutTime.name.like("%"+timeName+"%"));

        List<GateOutTime> gateOutTimes =
                queryFactory
                        .select(qGateOutTime)
                        .from(qGateOutTime)
                        .where(booleanBuilder.getValue())
                        .fetch();
        List<GateOutTimeDTO> gateOutTimeDTOS = CopyUtil.copyList(gateOutTimes, GateOutTimeDTO.class);
        gateOutTimeDTOS.stream().forEach(gtd -> {
            CompanyDTO companyDTO = companyService.findByCompanyId(gtd.getBaseId());
            gtd.setName(companyDTO.getCompanyName());
        });
        return gateOutTimeDTOS;

    }

}
